import { Component } from "cc";
import JNSyncFrame, { JNFrameInfo } from "../JNSyncFrame";
import JNFrameTween from "./tween/JNFrameTween";


export default abstract class JNSyncFrameComponent<Input extends {}> extends Component{

    private _nId:number;

    private _input:Input;
    get input(){
        if(!this._input){
            //初始化一个输入
            this._input = {} as Input;
        }
        return this._input;
    }

    get nId(){
        return this._nId;
    }

    //清空输入
    clearInput(){
        this._input = null;
    }
    //判断是否输入
    isInput():boolean{
        return !(!this._input || Object.keys(this._input).length == 0);
    }

    //是否初始化完成
    isSyncInitSuccess:boolean = false;

    //初始化完成
    public onSyncInitSuccess(){}

    //帧同步
    abstract onSyncUpdate(dt:number,frame:JNFrameInfo,input?:Input);

    //加载
    abstract onSyncLoad();

    //获取同步类
    protected abstract getSync():JNSyncFrame;

    onLoad(){
        //将组件添加到 JNSyncFrame
        this._nId = this.getSync().nSyncID();
        this.getSync().addSyncActor(this);
        this.onSyncLoad();
    }
    
    //解析
    decoder(bytes:Uint8Array):Input{
        return JSON.parse(new TextDecoder().decode(bytes))
    }

    //编码
    encoder(input:Input):Uint8Array{
        return new TextEncoder().encode(JSON.stringify(input));
    }

    JTween<T>(data:T){
        return new JNFrameTween<T>(data,this.node);
    }

    //销毁
    onDestroy(){
        this.getSync().delSyncActor(this);
    }

}


